import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Register from '@/views/register'
import Layout from '@/views/layout'
import Home from '@/views/home'
import Article from '@/views/article'
import ArticleCate from '@/views/article/article-cate'
import User from '@/views/user'
import UserAvatar from '@/views/user/user-avatar'
import UserPwd from '@/views/user/user-pwd'

import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: '/register',
      component: Register
    },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: Home
        },
        {
          path: '/art-list',
          component: Article
        },
        {
          path: '/art-cate',
          component: ArticleCate
        },
        {
          path: '/user-info',
          component: User
        },
        {
          path: '/user-avatar',
          component: UserAvatar
        },
        {
          path: '/user-pwd',
          component: UserPwd
        }
      ]
    }
  ]
})

// 白名单列表，记录无需权限访问的所有页面
const whileList = ['/login','/register']

router.beforeEach((to,from,next) => {
  const token = getToken()
  // 如果有token直接放行
  if (token) {
    next()
  } else {
    // 没有token的人，看看你要去哪
    // 判断白名单中是否存在
    if (whileList.includes(to.path)) {
      next()
    } else {
      // 否者拦截到登陆
      next('/login')
    }
  }
})

export default router
